
use tauri::{
    menu::{Menu, MenuItem},
    tray::{TrayIcon, TrayIconEvent, TrayIconBuilder, MouseButton},
    Manager,
};

pub fn set_tray(app: &tauri::App) -> Result<TrayIcon, tauri::Error> {
    let quit_i = MenuItem::with_id(app, "quit", "退出", true, None::<&str>).unwrap();
    let show_i = MenuItem::with_id(app, "show", "显示应用", true, None::<&str>).unwrap();
    let menu = Menu::with_items(
        app, 
        &[&show_i, &quit_i]
    ).unwrap();

    TrayIconBuilder::new()
        .icon(app.default_window_icon().unwrap().clone())
        .menu(&menu)
        .show_menu_on_left_click(false)
        .tooltip("EPassword")
        .on_menu_event(|app, event| match event.id.as_ref() {
            "quit" => {
                app.exit(0);
            },
            "show" => {
                let window = app.get_webview_window("main").unwrap();
                window.show().unwrap();
            },
            _ => {
                println!("menu item {:?} not handled", event.id);
            }
        })
        .on_tray_icon_event(|tray, event| match event {
            TrayIconEvent::DoubleClick  {
                button: MouseButton::Left,
                ..
            } => {
                let app = tray.app_handle();
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                }
            },
            _ => {}
        })
        .build(app)
}